﻿/*******************************************************
Copyright © 2009 Active Technologies Group, Inc. (ATGi)

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*******************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web.UI.WebControls;

using CommunityServer;
using CommunityServer.Components;
using CommunityServer.Controls;

using ATGi.CS.Facebook.Data;
using ATGi.CS.Facebook.Components;

namespace ATGi.CS.Facebook.Controls
{
    public class FacebookCreateUserSubForm : WrappedSubFormBase
    {
        FacebookLoginButton fbLoginButton;
        FacebookProfileImage profileImage;
        ResourceControl statusText;

        public string FacebookLoginButtonId
        {
            get { return (string)ViewState["FacebookLoginButtonId"] ?? string.Empty; }
            set { ViewState["FacebookLoginButtonId"] = value; }
        }

        public string LoggingInUsingTextResourceName
        {
            get { return (string)ViewState["LoggingInUsingTextResourceName"] ?? string.Empty; }
            set { ViewState["LoggingInUsingTextResourceName"] = value; }
        }

        public string LoggingInUsingTextResourceFile
        {
            get { return (string)ViewState["LoggingInUsingTextResourceFile"] ?? string.Empty; }
            set { ViewState["LoggingInUsingTextResourceFile"] = value; }
        }

        public string JoinMessageResourceControlId
        {
            get { return (string)ViewState["JoinMessageResourceControlId"] ?? string.Empty; }
            set { ViewState["JoinMessageResourceControlId"] = value; }
        }

        public string FacebookProfileImageId
        {
            get { return (string)ViewState["FacebookProfileImageId"] ?? string.Empty; }
            set { ViewState["FacebookProfileImageId"] = value; }
        }

        public string FacebookProfileNameLabelId
        {
            get { return (string)ViewState["FacebookProfileNameLabelId"] ?? string.Empty; }
            set { ViewState["FacebookProfileNameLabelId"] = value; }
        }

        public override bool IsEnabled()
        {
            return true;
        }

        public override bool IsValid()
        {
            CreateUserForm parentForm = (CreateUserForm)this.HostForm;
            CustomValidator CreateUserCustomValidator = CSControlUtility.Instance().FindControl(parentForm, parentForm.CreateUserCustomValidatorId) as CustomValidator;
            IFacebookUser fbUser = KernelContainer.Get<IFacebookUser>();
            if (fbUser.IsValid)
            {
                using (var dc = KernelContainer.Get<ATGi.CS.Facebook.Data.FBDataContext>())
                {
                    if (dc.FacebookUsers.Where(fu => fu.FacebookID == fbUser.ID).Count() != 0)
                    {
                        CreateUserCustomValidator.ErrorMessage = ResourceManager.GetString("Join_Facebook_AccountAlreadyInUse", "ATGi.xml");
                        CreateUserCustomValidator.IsValid = false;
                        return false;
                    }
                }
            }
            return true;
        }

        protected override void AttachChildControls()
        {
            fbLoginButton = CSControlUtility.Instance().FindControl(this, FacebookLoginButtonId) as FacebookLoginButton;
            statusText = CSControlUtility.Instance().FindControl(this, JoinMessageResourceControlId) as ResourceControl;
            profileImage = CSControlUtility.Instance().FindControl(this, FacebookProfileImageId) as FacebookProfileImage;
            
            if (this.HostForm is CreateUserForm && KernelContainer.Get<IFacebookUser>().IsValid)
                PopulateParentForm();
        }

        private void PopulateParentForm()
        {
            // Get the Facebook User information, if null or invalid, we want to form to render normally.
            // Otherwise we change things around based on the current user.
            IFacebookUser fbUser = KernelContainer.Get<IFacebookUser>();
            if (!fbUser.IsValid)
                return;

            fbLoginButton.Visible = false;
            
            CreateUserForm parentForm = (CreateUserForm)this.HostForm;
            string passwordText = MemberRoleProfileProvider.Instance().Members.GeneratePassword(8, 2);

            TextBox email = CSControlUtility.Instance().FindControl(parentForm, parentForm.EmailAddressTextBoxId) as TextBox;
            TextBox username = CSControlUtility.Instance().FindControl(parentForm, parentForm.UserNameTextBoxId) as TextBox;
            TextBox email2 = CSControlUtility.Instance().FindControl(parentForm, parentForm.SecondEmailAddressTextBoxId) as TextBox;
            TextBox password = CSControlUtility.Instance().FindControl(parentForm, parentForm.PasswordTextBoxId) as TextBox;
            TextBox password2 = CSControlUtility.Instance().FindControl(parentForm, parentForm.SecondPasswordTextBoxId) as TextBox;
            IButton createAccount = CSControlUtility.Instance().FindButtonControl(parentForm, parentForm.CreateButtonId);
            DropDownList timezone = CSControlUtility.Instance().FindControl(parentForm, parentForm.TimeZoneDropDownListId) as DropDownList;
            CommunityServer.Controls.PlaceHolder passwordPlaceholder = CSControlUtility.Instance().FindControl(parentForm, parentForm.PasswordPlaceholderId) as CommunityServer.Controls.PlaceHolder;

            if (username != null && string.IsNullOrEmpty(username.Text) && fbUser.Name != null && !string.IsNullOrEmpty(fbUser.Name))
                username.Text = fbUser.Name.ToLowerInvariant().Replace(" ", string.Empty);
            
            if (password != null)
            {
                password.Attributes.Add("value", passwordText);
                password.Visible = false;
            }
            if (password2 != null)
            {
                password2.Attributes.Add("value", passwordText);
                password2.Visible = false;
            }

            if (passwordPlaceholder != null)
                passwordPlaceholder.Visible = false;

            if (createAccount != null && createAccount.Attributes["disabled"] != null && email != null && email2 != null 
                && username != null && fbUser != null && !string.IsNullOrEmpty(fbUser.Name))
                createAccount.Attributes.Remove("disabled");

            // Change attributes of things on the form to display only the bits needed for signin at this point.
            if (statusText != null)
            {
                statusText.ResourceName = this.LoggingInUsingTextResourceName;
                statusText.ResourceFile = this.LoggingInUsingTextResourceFile;
            }
            if (profileImage != null) 
                profileImage.Visible = true;

            // Hide other subforms
            // HACK: (JJE) reflecting private subforms list on HostForm form.
            List<WrappedSubFormBase> subForms = (List<WrappedSubFormBase>)
                ((PropertyInfo)HostForm.GetType()
                    .GetMember("InternalSubForms", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetProperty).GetValue(0))
                    .GetValue(HostForm, null);
            foreach (WrappedSubFormBase b in subForms)
            {
                if (b.UniqueID != this.UniqueID)
                {
                    b.Visible = false;
                }
            }
        }

        public override void ApplyChangesAfterCommit(object activeObject)
        {
            // Associate Facebook user with user created from FB account.
            User user = activeObject as User;
            IFacebookUser fbUser = KernelContainer.Get<IFacebookUser>();
            IFacebookSession facebook = KernelContainer.Get<IFacebookSession>();

            User updatedUser = FacebookUsers.AssociateFacebookUser(user, fbUser, facebook);

            user.AvatarUrl = updatedUser.AvatarUrl;
            user.EnableAvatar = updatedUser.EnableAvatar;
        }

        public override void ApplyChangesBeforeCommit(object activeObject)
        {
            User user = activeObject as User;

            if (user != null && Globals.IsNullorEmpty(user.Password))
                user.Password = MemberRoleProfileProvider.Instance().Members.GeneratePassword(8, 2);

            base.ApplyChangesBeforeCommit(activeObject);
        }

    }
}
